layui.define(function(exports) {
	function WebSocketUtils() {};
	WebSocketUtils.prototype = {
		constructor: WebSocketUtils,
		/**
		 * @author: ares
		 * @date: 2018/5/8 15:26
		 * @description: 初始化websocket
		 * @param {string} baseURL            连接ip及端口,连接路径
		 * @param {Object} urlParams          请求参数
		 * @returns {WebSocket}
		 */
		init:  function(baseURL, urlParams) {
			let webSocketBaseUrl = "ws://" + location.hostname + ':' + location.port,
				baseUrl = baseURL ? ("ws://" + baseURL) : webSocketBaseUrl,
				paramsStr = '',
				str = '';
			if (Object.prototype.toString.call(urlParams) == '[object Object]') {
				for (let param in urlParams) {
					str += ('&' + param + '=' + urlParams[param]);
				}
				paramsStr += ('?' + str.slice(1));
			}
			if (paramsStr == '?') paramsStr = '';
			let webSocketUrl = baseUrl + paramsStr;
			console.log('>> websocket address <<', webSocketUrl);
			return new WebSocket(webSocketUrl);
		},
		/**
		 * @author: ares
		 * @date: 2018/11/11 13:39
		 * @description: 声明webSocket
		 * @param {string} baseURL              连接ip及端口,连接路径
		 * @param {Object} urlParams            请求参数
		 * @param {string} type                 哪一个webSocket
		 * @param {function} onmessageCallBack  webSocket收到消息时的回调
		 */
		Declare: function(baseURL, urlParams, type, onmessageCallBack) {
			let self = this;
			this.socket = initWebSocket(baseURL, urlParams);
			this.type = type;
			this.onmessageCallBack = onmessageCallBack;
			this.socket.onopen = function(event) {
				if (typeof self.onopenCallBack == 'function') {
					self.onopenCallBack(event);
				} else {
					console.log('>> ' + self.type + ' websocket服务器连接成功 <<');
				}
			};
			this.socket.onmessage = function(event) {
				if (typeof self.onmessageCallBack == 'function') {
					self.onmessageCallBack(event);
				} else {
					console.log('>> ' + self.type + ' websocket服务器收到消息 <<', event);
				}
			};
			this.socket.onclose = function(event) {
				if (typeof self.oncloseCallBack == 'function') {
					self.oncloseCallBack(event);
				} else {
					console.error('>> ' + self.type + ' websocket服务器断开连接 <<', event);
				}
			};
			this.socket.onerror = function(event) {
				if (typeof self.onerrorCallBack == 'function') {
					self.onerrorCallBack(event);
				} else {
					console.error('>> ' + self.type + ' websocket发生错误 <<', event);
				}
			}
		}
	};
	exports('webSocket',new WebSocketUtils());
})














